package com.demo.config.watermark;

import cn.hutool.core.util.StrUtil;
import lombok.Data;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * 根据文字生成水印图片
 */
public class FontImage {

	@Data
	public static class Watermark {

		private Boolean enable;

		private String text;

		private String dateFormat;

		private String color;

	}

	public static BufferedImage createWatermarkImage(Watermark watermark) {
		if (watermark == null) {
			watermark = new FontImage.Watermark();
			watermark.setEnable(true);
			// watermark.setText("userName");
			watermark.setText("水印测试");
			watermark.setColor("#C5CBCF");
			watermark.setDateFormat("yyyy-MM-dd HH:mm");
		}
		else {
			if (StrUtil.isEmpty(watermark.getDateFormat())) {
				watermark.setDateFormat("yyyy-MM-dd HH:mm");
			}
			else if (watermark.getDateFormat().length() == 16) {
				watermark.setDateFormat("yyyy-MM-dd HH:mm");
			}
			else if (watermark.getDateFormat().length() == 10) {
				watermark.setDateFormat("yyyy-MM-dd");
			}
			if (StrUtil.isEmpty(watermark.getText())) {
				watermark.setText("水印测试");
			}
			if (StrUtil.isEmpty(watermark.getColor())) {
				watermark.setColor("#C5CBCF");
			}
		}
		String[] textArray = watermark.getText().split("\n");
		Font font = new Font("microsoft-yahei", Font.PLAIN, 50);
		Integer width = 200;
		Integer height = 200;

		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		// 背景透明 开始
		Graphics2D g = image.createGraphics();
		image = g.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
		g.dispose();
		// 背景透明 结束
		g = image.createGraphics();
		g.setColor(new Color(Integer.parseInt(watermark.getColor().substring(1), 16)));// 设定画笔颜色
		g.setFont(font);// 设置画笔字体
		g.shear(0.1, 0.5);// 设定倾斜度

		// 设置字体平滑
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

		int y = 50;
		y = y + font.getSize();
		// for (int i = 0; i < textArray.length; i++) {
		// g.drawString(textArray[i], 0, y);// 画出字符串
		// y = y + font.getSize();
		// }
		g.drawString(watermark.getText(), 0, y);// 画出字符串

		g.dispose();// 释放画笔
		return image;

	}

}
